<?php

namespace addons\third\library;

use addons\third\model\Third;
use app\common\model\User;
use think\Db;
use think\exception\PDOException;
use think\Cookie;

/**
 * 第三方登录服务类
 *
 * @author Karson
 */
class Service
{

    /**
     * 第三方登录
     * @param string $platform 平台
     * @param array $params 参数
     * @param array $extend 会员扩展信息
     * @param int $keeptime 有效时长
     * @return boolean
     */
    public static function connect($platform, $params = [])
    {
        $time = time();
        $values = [
            'platform'      => $platform,
            'openid'        => $params['openid'],
            'openname'      => isset($params['userinfo']['nickname']) ? $params['userinfo']['nickname'] : '',
            'access_token'  => $params['access_token'],
            'refresh_token' => $params['refresh_token'],
            'expires_in'    => $params['expires_in'],
            'logintime'     => $time,
            'expiretime'    => $time + $params['expires_in'],
        ];
        Cookie::set('medical_third', $values);

        $third = Third::get(['platform' => $platform, 'openid' => $params['openid']]);
        if ($third) {
            if ($third['user_id']) {
                Cookie::set('medical_third', json_decode($third, true));
            }
            $third->save($values);
            return TRUE;
        } else {
            Db::startTrans();
            try {
                Third::create($values);
                Db::commit();
                return TRUE;
            } catch (PDOException $e) {
                Db::rollback();
                return FALSE;
            }
        }
    }

}
